home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15227 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  82 lines

  1. Path: grimsel.zurich.ibm.com!usenet
  2. From: wgk@zurich.ibm.com (Keith Whittingham)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Is this a memory leak?
  5. Date: 4 Apr 1996 08:58:13 GMT
  6. Organization: IBM Research, ZRH
  7. Message-ID: <4k02v5$tu7@grimsel.zurich.ibm.com>
  8. References: <4jv214$gv7@insosf1.netins.net>
  9. Reply-To: wgk@zurich.ibm.com
  10. NNTP-Posting-Host: pine.zurich.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.00
  12.  
  13. In <4jv214$gv7@insosf1.netins.net>, hhowe@trgnet.com (Harold Howe) writes:
  14. >Could someone please tell me if this code leaks memory
  15. >
  16. >class BuriedClass
  17. >  {
  18. >  ...
  19. >  }
  20. >
  21. >class TopClass
  22. >  {
  23. >  private
  24. >    BuriedClass *bury;
  25. >  public:
  26. >    TopClass::TopClass() { bury = new BuriedClass();}
  27. >    shutDown             { bury = 0;}
  28. >    ~TopClass            { delete bury}
  29. >  }
  30. >
  31. >int main(void)
  32. >  {
  33. >  TopClass *top = new TopClass();
  34. >  top->shutDown();
  35. >  delete top;
  36. >  return 0;
  37. >  }
  38. >
  39. Yup, memory leak alright!
  40.  
  41. The ctor allocates a block of memory for the BuriedClass, probably calling
  42. a malloc(). "bury" is a variable which is set to point at that memory, i.e
  43. it is assigned a value equal to the address of the allocated memory.
  44.  
  45. The shutDown method does nothing more or less than assigning a value of
  46. 0 to the bury variable - the is no delete/free of the memory.
  47.  
  48. The dto, ~TopClass, is a going to try and free some memory at the address
  49. 0x000 but, by a quirk of implmentation, will probably not blow up (as a 
  50. simple call to free(0) would). Instead the compiler probably generates
  51. code to check that the object address is 0, it so there is no deallocation
  52. of the memory.
  53.  
  54. Better to forget about the shutdown function and either to simply declare 
  55. bury as a member variable:
  56.  
  57.   class TopClass
  58.     {
  59.     private
  60.       BuriedClass bury;    // note no '*'
  61.     public:
  62.       TopClass::TopClass() { }
  63.       ~TopClass            { }
  64.   }
  65.  
  66. or if you really want to do it dynamically...
  67.  
  68.   class TopClass
  69.     {
  70.     private
  71.       BuriedClass *bury; 
  72.     public:
  73.       TopClass::TopClass() { bury = new BuriedClass; }
  74.       ~TopClass            { delete bury; }
  75.   }
  76.  
  77.  
  78. The first approach is better.
  79.  
  80. Keith
  81.  
  82.